var train_role_modify = new Object();
train_role_modify.courses = [];
train_role_modify.courseIds = [];
train_role_modify.init = function ( basePath, page, options) {
    var courseIds = $("#courseIds").val();
    if("" != courseIds){
        train_role_modify.courseIds = courseIds.split(",");
    }

    //人员的操作
    train_role_modify.handle();
    //展示已经的课程列表数据
    train_role_modify.initTable();
   
}
var userIdAll = [];
var object = {};
/**
 * 全选事件
 */
$("#checkAll").click(function () {
        if (this.checked) {
            $("#select_course_list :checkbox").prop("checked", true);

            $("#select_course_list :checkbox").each(function () {
                if (!object[$(this).val()]) {
                    object[$(this).val()] = 1;
                    userIdAll.push($(this).val());
                }
            });
        } else {
            $("#select_course_list :checkbox").prop("checked", false);
            if (userIdAll.length > 0) {
                for (var a = 0; a < userIdAll.length; a++) {
                    $("#select_course_list :checkbox").each(function () {
                        if ($(this).val() === userIdAll[a]) {
                            delete object[$(this).val()];
                            userIdAll.splice(a, 1);
                        }
                    })
                }
            }
        }
        // console.log(userIdAll);
    }
);

/**
 * 单选事件
 */
$("#select_course_list").on("click", "input[type=checkbox]", function () {
    if ($(this).is(":checked")) {
        if (!object[$(this).val()]) {
            object[$(this).val()] = 1;
            userIdAll.push($(this).val());
        }
    } else {
        if (userIdAll.length > 0) {
            for (var a = 0; a < userIdAll.length; a++) {
                if ($(this).val() === userIdAll[a]) {
                    delete object[$(this).val()];
                    userIdAll.splice(a, 1);
                }
            }
        }
    }
    //  console.log(userIdAll);
});
/**
 *
 * 清空所有的选择
 */
$("#clearSelAll").on("click", function () {
    object={};
    userIdAll = [];
});

train_role_modify.handle = function () {
    //弹窗-选择课程
    $("#btn_dialog_course").click(function () {
        // 调用选择培训课程的弹窗
        layer.open({
            type: 2,
            title: '选择课程',
            area: ['1200px', '80%'],		//弹出层大小
            scrollbar: false,				//false隐藏滑动块
            content: [appPath + '/admin/trainRole/selectCourse', 'yes']
        });

        /*layer.open({
            type: 2,
            title: '选择课程',
            area: ['1200px', '80%'],		//弹出层大小
            scrollbar: false,				//false隐藏滑动块
            content: [appPath + '/popup/enterSelectCourse', 'yes']
        });*/
    });



 /*   $("#all").click(function () {
        if (this.checked) {
            $("#select_course_list :checkbox").prop("checked", true);
        } else {
            $("#select_course_list :checkbox").prop("checked", false);
        }
    });*/




    $("#btn_search_course").click(function () {
        train_role_modify.initTable();
    });
    $("#btn_search_all_course").click(function () {
        $("#courseName").val("");
        train_role_modify.initTable();
    });

    train_role_modify.search = function () {
        train_role_modify.initTable();
    };

//保存


    $("#saveSet").click(function () {
        var questionNum = $.trim($("#questionNum").val())
        if ("" == questionNum) {
            layer.msg("请填写题量");
            return;
        }
        if (questionNum.length > 4) {
            layer.msg("题量位数不能超过4");
            return;
        }


   /*     var chooseType = $("input[name='chooseType']:checked").val();

        console.log("----train_role_modify.courses.length---------", train_role_modify.courses.length)
        console.log("chooseType-----------------", chooseType)
        if ("2" == chooseType && train_role_modify.courses.length == 0) {
            layer.msg("请选择课程");
            return;
        }

        //选中的课程
        var courseIds = [];
        for (var i = 0; i < train_role_modify.courses.length; i++) {
            courseIds.push(train_role_modify.courses[i].course_id)
        }
        $("#courseIds").val(courseIds);


        console.log("courseIds", $("#courseIds").val())*/
        var url = appPath + "/admin/trainRole/saveSet";
        var opt = {
            url: url,
            type: "post",
            dataType: "json",
            success: function (data) {
                var result = data.code;
                if ("10000" == result) {
                    layer.msg("保存成功")
                    // window.location.href = appPath + "/admin/trainRole"
                    window.location.href = appPath + "/admin/trainRole/day_practise_set"
                }
            }
        };
        $("#set_form").ajaxSubmit(opt);
    })


    $("#save").click(function () {
        var roleName = $("#roleName").val()
        if ("" == roleName) {
            layer.msg("请填写角色名称")
            return;
        }
        if (roleName.length>15) {
            layer.msg("角色名称请少于15字")
            return;
        }

        var url = appPath + "/admin/trainRole/update"
        //$("#trainsubject_form").attr("action",url);
        var opt = {
            url: url,
            type: "post",
            dataType: "json",
            success: function (data) {
                result = data.code;
                if ("10000" == result) {
                    window.location.href = appPath + "/admin/trainRole"
                }else if(50520 == result){
                    layer.msg("角色名称已重复请重置");
                }
            }
        }
        $("#trainrole_form").ajaxSubmit(opt);
    });

    //删除课程
    $("#btn_delete_batch_course").click(function () {
        train_role_modify.delete_train_role_course();
    })
}

//查询主题下的所有课程
train_role_modify.initCourse = function () {
    var varId = $("#varId").val();
    /**/
    $.ajax({
        url: appPath + "/admin/trainRole/allCourse",
        type: 'post',
        data: {"varId": varId},
        success: function (data) {
            if (10000 == data.code) {
                train_role_modify.courseIds = data.result;
                //console.log("==已有的课程id=" + data.result);
            }
        }
    });
}
train_role_modify.initTable = function () {

    $("#checkAll").attr("checked", false);
    var list_url = appPath + "/admin/trainRole/course_set";
    page.init("select_course_form", list_url, "select_course_list", "select_course_page", 1, 10);
    page.goPage(1);
    page.list = function (dataList) {

        var len = dataList.length;
        items = dataList;
        var inner = "", item;
        for (var i = 0; i < len; i++) {
            // 组装数据
            item = dataList[i];
            inner += '<tr>';
            inner += '<td><input type="checkbox"  name="ckbox" data-courseId="' + item.course_id + '"  value="' + item.course_id + '" /></td>';
            inner += '<td>';
            inner += '<span>' + item.course_no + '</span>';
            inner += '</td>';
            inner += '<td>' + item.course_name + '</td>';
           /* inner += '<td>' + item.class_hour + '</td>';
            inner += '<td><a href="javascript:;" onclick=\"train_role_modify.course_view(\'' + item.course_id + '\');\" class="a a-info">课程预览</a>';
            inner += ' <a href="javascript:;" onclick=\"train_role_modify.question_view(\'' + item.course_id + '\');\" class="a a-view">题库预览</a></td>';*/
            inner += '</tr>';
        }
        return inner;
    }
    //查询所有课程
    //train_role_modify.initCourse()
};
// 批量删除课程
train_role_modify.delete_train_role_course = function () {

    var courseIds = userIdAll;
    console.log("----------courseIds---------",courseIds.length)
    if (courseIds.length == 0) {
        layer.msg("未选择课程1");
        return;
    }

    train_role_modify.remove(courseIds);

  /*  layer.confirm("确定执行此操作?", {
        icon: 3,
        btn: ["确认", "取消"]
    }, function () {

        /!* userIdAll=[];
         object={}*!/
    });*/
};


// 选择培训课程的回调
train_role_modify.submitCourse = function (rows) {
    var varId = $("#varId").val();
    if (rows.length < 1) {
        return;
    }
    for (i = 0; i < rows.length; i++) {
        train_role_modify.removeRepart(train_role_modify.courseIds, rows[i].course_id);
    }

    console.log("==选择id=" + train_role_modify.courseIds);
    /*修改*/
    $.ajax({
        url: appPath + "/admin/trainRole/updateSetCourse",
        type: 'post',
        data: {"intTrainRoleId": varId, "courseIds": train_role_modify.courseIds.join(',')},
        success: function (data) {
            if (10000 == data.code) {
                console.log("=== ok 修改成功=======");
                $("#courseIds").val(train_role_modify.courseIds.join(','));
                train_role_modify.initTable();
            }
        }
    });

}


// 课程信息列表
train_role_modify.train_subject_course = function () {
    var len = train_role_modify.courses.length;
    var length = $("#select_course_list").parent().find("th").length;
    if (len < 1) {
        $("#select_course_list").empty().html(train_role_modify.noList(length));
        return
    }
    var inner = "", item;
    // 组装数据
    for (var i = 0; i < len; i++) {
        item = train_role_modify.courses[i];
        inner += '<tr >';
        inner += '<td>' + (i + 1) + '</td>';
        inner += '<td><input type=\"checkbox\" name="courseBox" data-courseId="' + item['course_id'] + '" data-id="' + item['id'] + '"></td>';
        inner += '<td>' + item['course_no'] + '</td>';
        inner += '<td><span class="text-orange">' + item['course_name'] + '</span></td>';
      /*  inner += '<td>' + item['class_hour'] + '</td>';*/
   /*     inner += '<td>';
        inner += '<a href="javascript:;" onclick=\"train_role_modify.course_view(\'' + item.course_id + '\');\" class="a a-info">课程预览</a>';
        inner += ' <a href="javascript:;" onclick=\"train_role_modify.question_view(\'' + item.course_id + '\');\" class="a a-view">题库预览</a>';
        inner += '</td>';*/
        inner += '</tr>';
    }

    // 渲染表单
    $("#select_course_list").empty().html(inner);

};


//课程预览
train_role_modify.course_view = function (course_id) {
    common.goto_student_course_view(course_id);
}

//试题预览
train_role_modify.question_view = function (course_id) {
    common.goto_student_course_question_view(course_id);
}

//课程数组合并去重
train_role_modify.removeRepart = function (courseIds, courseId) {
    var flag = true;
    for (var i = 0; i < courseIds.length; i++) {
        if (courseIds[i] == courseId) {
            flag = false;
        }
    }
    if (flag) {
        train_role_modify.courseIds.push(courseId);
    }
}

//删除课程
train_role_modify.remove = function (courseIds) {

    for(var i=0;i< train_role_modify.courseIds.length;i++){
        for(var j=0;j< courseIds.length;j++){
            if(train_role_modify.courseIds[i] == courseIds[j]){
                train_role_modify.courseIds.splice(i,1);
            }
        }
    }

    // var varId = $("#varId").val();
    $.ajax({
        url: appPath + "/admin/trainRole/updateSetCourse",
        type: 'post',
        data: {"courseIds": train_role_modify.courseIds.join(',')},
        success: function (data) {
            if (10000 == data.code) {
                layer.msg("删除成功");
                $("#courseIds").val(train_role_modify.courseIds.join(','));
                train_role_modify.initTable();
            }
        }
    });
};

train_role_modify.noList = function (length) {
    var inner = "";
    inner += "<tr>";
    inner += '<td colspan=\'' + length + '\' class=\"table_empty\"><img src=\'' + empty_img_src + '\'></img></td>'
    inner += "</tr>";
    return inner;
}